<!DOCTYPE html>
<title>Service Worker: WindowClient.focus() tests (using testRunner)</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<script>
// This test is using testRunner to grant itself the notification permission and
// to simulate a click on a notification. A couple of changes would allow it to
// be run as a manual test by other browser vendors.
if (window.testRunner)
    testRunner.setPermission('notifications', 'granted', location.origin, location.origin);

var t = async_test('WindowClient.focus() behaved as expected');
t.step(function() {
    var scope = 'resources/windowclient-focus.html'
    service_worker_unregister_and_register(
        t, 'resources/windowclient-focus.js', scope)
      .then(function(registration) {
          return wait_for_state(t, registration.installing, 'activated');
        })
      .then(function() { return with_iframe(scope); })
      .then(function(frame) {
          var w = frame.contentWindow;
          w.navigator.serviceWorker.onmessage = t.step_func(onMessage);
          w.navigator.serviceWorker.controller.postMessage('start');
        })
      .catch(unreached_rejection(t));

    var result = [];
    var expected = [
        'focus() can\'t focus a window without a user interaction',
        'focus() error is InvalidAccessError',
        'focus() succeeded',
        'focus() result: [object WindowClient]',
        ' visibilityState: visible',
        ' focused: true',
        ' url is the same',
        ' frameType is the same',
        'focused clients: 1',
        'focus() succeeded',
        'focus() result: [object WindowClient]',
        ' visibilityState: visible',
        ' focused: true',
        ' url is the same',
        ' frameType is the same',
        'focused clients: 2',
        'focus() succeeded',
        'focus() result: [object WindowClient]',
        ' visibilityState: visible',
        ' focused: true',
        ' url is the same',
        ' frameType is the same',
        'focused clients: 2',
        'focus() succeeded',
        'focus() result: [object WindowClient]',
        ' visibilityState: visible',
        ' focused: true',
        ' url is the same',
        ' frameType is the same',
        'focused clients: 1',
    ];

    function onMessage(e) {
        var message = e.data;

        if (typeof(message) === 'object') {
            if (message.type !== 'click')
                return;
            if (window.testRunner)
                testRunner.simulateWebNotificationClick(message.title);
            return;
        }

        if (message === 'quit') {
            assert_array_equals(result, expected,
                                'Worker should post back expected messages.');
            service_worker_unregister_and_done(t, scope);
        } else {
            result.push(message);
        }
    }
  });
</script>
